<template>
  <el-upload class="avatar-uploader"
             action="/api/UploadMedia"
             :show-file-list="false"
             :on-success="handleAvatarSuccess"
             :before-upload="beforeAvatarUpload">
    <img v-if="isUpload"
         :src= "imageUrl"
         class="avatar"
         crossOrigin="anonymous"/>
    <img v-else src="../../assets/img/upload.png"
         class="unUpload"/>
  </el-upload>
</template>
<script>
export default {

   //props 父传子
   props:['avatarImg'],
    data() {
        return {
            isUpload: false,//? 获取当前用户是否已上传头像
            imageUrl: ''
        };
    },
    mounted(){
      console.log(this.avatarImg);
    },
    methods: {
        changeImg(res) {
          //子传父 $emit
            this.$emit('imageUrlChange', res);
        },
        handleAvatarSuccess(res) {
            this.imageUrl = 'http://' + res.data;
            this.isUpload = 'true';
            this.changeImg(this.imageUrl);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }
    }
};
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 200px;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.unUpload {
    width: 100px;
    height: 100px;
    position: relative;
    top: 20%;
}
.avatar {
    width: 200px;
    height: 185px;
    align-items: center;
    justify-content: center;
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center center;
}
.uploadCover .el-upload--text {
    height: 150px;
    width: 200px;
}
</style>
